<template>
  <div>
    <h1>33</h1>
    <div class="panel panel-primary">
      <div class="panel-heading">
        <h3 class="panel-title">添加品牌</h3>
      </div>

      <div class="panel-body form-inline">
        <label
          >Id:<input type="text" class="form-control" v-model="id" />
        </label>
        <label>
          Name:<input type="text" class="form-control" v-model="name"
        /></label>
        <!-- 在Vue中，使用事件绑定机制，为元素指定处理函数的时候，如果加了小括号，就可以给函数传参了 -->
        <input
          type="button"
          value="添加"
          class="btn btn-primary"
          @click="add()"
        />
        <label>
          搜索名称关键字：
          <input type="text" class="form-control" v-model="keywords"
        /></label>
      </div>
      <table class="table table-bordered table-hover table-striped">
        <thead>
          <tr>
            <th>Id</th>
            <th>Name</th>
            <th>Ctime</th>
            <th>Operation</th>
          </tr>
        </thead>
        <tbody>
          <!-- 通过search方法渲染数据，而是直接通过从data上面获取数据直接进行渲染 -->
          <tr v-for="item in search(keywords)" :key="item.id">
            <td>{{ item.id }}</td>
            <td v-text="item.name"></td>
            <td>{{ item.ctime }}</td>
            <td>
              <a href="" @click.prevent="del(item.id)">删除</a>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      id: "",
      name: "",
      keywords: "",
      list: [
        { id: 2021, name: "奥迪", ctime: new Date() },
        { id: 2022, name: "奔驰", ctime: new Date() },
      ],
    };
  },
  created() {
    this.add();
    this.del();
    this.search();
  },
  methods: {
    add() {
      var car = { id: this.id.name, name: this.name, ctime: new Date() };
      this.list.push(car);
      this.id = this.name = "";
    },
    del(id) {
      var index = this.list.findIndex((item) => {
        if (item.id == id) {
          return true;
        }
      });
      this.list.splice(index, 1);
    },
    search(keywords) {
      return this.list.filter((item) => {
        if (item.name.includes(keywords)) {
          return item;
        }
      });
    },
  },
};
</script>
<style scoped>
</style>